package com.UnionPayCenter.service.serviceImpl;


import com.UnionPayCenter.constant.ConstantInterface;
import com.UnionPayCenter.entity.*;
import com.UnionPayCenter.entity.vo.ManagerVo;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.exception.ApiException;
import com.UnionPayCenter.jwt.ITokenManager;
import com.UnionPayCenter.mapper.ManagerMapper;
import com.UnionPayCenter.redis.IRedisService;
import com.UnionPayCenter.service.IManagerService;
import com.UnionPayCenter.util.MD5Util;
import com.UnionPayCenter.util.StringUtils;
import com.UnionPayCenter.wechat.WXCardSignatureUtil;
import com.UnionPayCenter.vastchain.SmsUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @Description:
* @Param:
* @return:
* @Author: bite
* @Date: 2019/4/25
*/
@Service
@Transactional
public class ManagerServiceImpl implements IManagerService {
    @Autowired
    private ManagerMapper managerMapper;
    @Resource
    private ITokenManager tokenManager;
    @Autowired
    private IRedisService redisService;

    @Override
    public ManagerVo login(JSONObject jsonParam) {
        String username = jsonParam.getString("username");
        String password = jsonParam.getString("password");

        //密码加密
        String encryptPwd = MD5Util.getMD5StrByBB(password);
        //查询用户名是否存在
        ManagerVo manager = managerMapper.login(username, encryptPwd);
        if(manager == null){
            int count = managerMapper.countByUsername(username);
            if(count == 0){
                throw new ApiException(ErrorCodeEnum.SW50);
            }else{
                throw new ApiException(ErrorCodeEnum.SW30);
            }
        }

        Map<String, Object> clamis = new HashMap<>();
        clamis.put("userId", manager.getManagerId());
        String token = tokenManager.createToken(manager.getManagerId(), manager.getUsername(), clamis).getToken();
        if(StringUtils.isNullStr(token)){
            throw new ApiException(ErrorCodeEnum.TK1003);
        }
        manager.setToken(token);
        return manager;
    }

    @Override
    public boolean loginOut(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        redisService.deleteString(ConstantInterface.TOKEN_REDIS_KEY + managerId);
        return true;
    }

    @Override
    public ManagerEntity getInfo(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        ManagerEntity managerEntity = managerMapper.selectManager(managerId);
        return managerEntity;
    }

    @Override
    public boolean getVerificationCode(JSONObject jsonParam) {
        String mobile = jsonParam.getString("mobile");
        Integer type = jsonParam.getInteger("type");
        String verifyCode = String.valueOf((int) Math.round(Math.random() * (9999 - 1000) + 1000));
        SmsUtil.sendVerificationCodeMsg(verifyCode, mobile);
        if(type == 0) {
            redisService.setString("mr:" + mobile, verifyCode, 5, TimeUnit.MINUTES);
        }else if(1== type){
            redisService.setString("mf:" + mobile, verifyCode, 5, TimeUnit.MINUTES);
        }
        return true;
    }

    @Override
    public boolean registry(JSONObject jsonParam) {
        String code = jsonParam.getString("code");
        String password = jsonParam.getString("password");
        String mobile = jsonParam.getString("mobile");

        String mr = redisService.getString("mr:" + mobile);
        if(!code.equals(mr)){
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "验证码"));
        }
        try {
            ManagerEntity managerEntity = new ManagerEntity();
            managerEntity.setUsername(mobile);
            managerEntity.setPassword(MD5Util.getMD5StrByBB(password));
            managerEntity.setIsAdmin(1);
            managerMapper.insertSelective(managerEntity);
            return true;
        }catch (Exception e) {
            throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "手机号已存在，注册"));
        }
    }

    @Override
    public boolean chenMobile(JSONObject jsonParam) {
        String mobile = jsonParam.getString("mobile");
        int count = managerMapper.countByUsername(mobile);
        return count == 0;
    }

    @Override
    public boolean forgetPassword(JSONObject jsonParam) {
        String code = jsonParam.getString("code");
        String password = jsonParam.getString("password");
        String mobile = jsonParam.getString("mobile");

        String mf = redisService.getString("mf:" + mobile);
        if(!code.equals(mf)){
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "验证码"));
        }
        try {
            int count = managerMapper.countByUsername(mobile);
            if(count == 0){
                throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "手机号未注册，修改"));
            }
            ManagerEntity managerEntity = new ManagerEntity();
            managerEntity.setUsername(mobile);
            managerEntity.setPassword(MD5Util.getMD5StrByBB(password));
            managerMapper.forgetPassword(managerEntity);
            return true;
        }catch (Exception e) {
            throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "手机号已存在，注册"));
        }
    }

	@Override
	public ManagerEntity saveCardNum(JSONObject jsonParam) {
        String mobile = jsonParam.getString("mobile");
        String code = jsonParam.getString("code");
        try {
            String cardNum = WXCardSignatureUtil.descryptCode("", "", code);
            if (StringUtils.isNullStr(cardNum)) {
                throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "会员卡号解密"));
            }
            ManagerEntity managerEntity = new ManagerEntity();
            managerEntity.setUsername(mobile);
            managerEntity.setCardNum(cardNum);
            managerMapper.saveCardNumber(managerEntity);
            return managerEntity;
        }catch (ApiException e) {
            throw e;
        }catch (Exception e) {
            throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "会员卡号保存"));
        }
	}
}
